<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from "@/utils/axios";
import { ElMessage, ElDialog } from 'element-plus'

const tableRef = ref()

const data = reactive({
  tableData: [],
  page: 1,
  limit: 20,
  total: 0,
  searchForm: {
    searchKey: 'email',
    searchValue: ''
  },
  sortBy: '', // 排序字段
  sortOrder: '' // 排序顺序
})

// 编辑用户状态的对话框数据
const editForm = reactive({
  showEdit: false,
  userId: 0,
  status: 1, // 默认正常
})

const init = async () => {
  let url = `/users/list?page=${data.page}&limit=${data.limit}`

  // 添加搜索参数
  if (data.searchForm.searchKey && data.searchForm.searchValue) {
    url += `&searchKey=${data.searchForm.searchKey}&searchValue=${encodeURIComponent(data.searchForm.searchValue)}`
  }

  // 添加排序参数
  if (data.sortBy && data.sortOrder) {
    url += `&sortBy=${data.sortBy}&sortOrder=${data.sortOrder}`
  }

  try {
    const res = await axios.get(url)
    // 根据实际返回的数据结构处理
    if (res.code === 200 && res.data) {
      data.tableData = res.data.records || []
      data.total = res.data.total || 0
    } else {
      console.warn("返回数据格式异常:", res)
      data.tableData = []
      data.total = 0
      ElMessage.error(res.msg || "数据加载失败")
    }
  } catch (error) {
    console.error("请求失败:", error)
    ElMessage.error("获取用户列表失败")
    // 清空数据，避免显示旧数据
    data.tableData = []
    data.total = 0
  }
}

const handleSearch = () => {
  data.page = 1 // 搜索时重置到第一页
  init()
}

const resetSearch = () => {
  data.searchForm.searchKey = 'email'
  data.searchForm.searchValue = ''
  data.page = 1
  init()
}

const jump = (val) => {
  data.page = val
  init()
}

const del = async (userId) => {
  try {
    const res = await axios.get("/users/removeByNo?userId=" + userId)
    // 根据 ResponseMsg.java 格式处理响应
    if (res.code === 200) {
      ElMessage({
        message: "操作成功！",
        type: "success",
        duration: 1000,
        onClose() {
          init();
        },
      })
    } else {
      ElMessage.error(res.msg || "删除失败")
    }
  } catch (error) {
    console.error("删除失败:", error)
    ElMessage.error("删除失败: " + (error.message || "未知错误"))
  }
}

const delSelected = async () => {
  try {
    const rows = tableRef.value.getSelectionRows() // 获取表中选中行
    const nids = rows.map(row => row.userId)
    console.log("nids:", nids)

    if (nids.length === 0) {
      ElMessage.warning("请先选择要删除的用户")
      return
    }

    const res = await axios.post("/users/removes", nids)
    // 根据 ResponseMsg.java 格式处理响应
    if (res.code === 200) {
      ElMessage({
        message: "操作成功！",
        type: "success",
        duration: 1000,
        onClose() {
          init();
        },
      })
    } else {
      ElMessage.error(res.msg || "批量删除失败")
    }
  } catch (error) {
    console.error("批量删除失败:", error)
    ElMessage.error("批量删除失败: " + (error.message || "未知错误"))
  }
}

// 处理排序变化
const handleSortChange = (sortInfo) => {
  data.sortBy = sortInfo.prop
  data.sortOrder = sortInfo.order === 'ascending' ? 'asc' : 'desc'
  init()
}

// 编辑用户状态
const editUserStatus = (row) => {
  // 设置编辑数据
  editForm.userId = row.userId
  editForm.status = row.status

  // 显示编辑对话框
  editForm.showEdit = true
}

// 编辑状态
const submitEdit = async () => {
  try {
    const users = {
      userId: editForm.userId,
      status: editForm.status,
    }

    const res = await axios.post("/users/up", users)
    if (res.code === 200) {
      ElMessage({
        message: "修改成功！",
        type: "success",
        duration: 1000,
        onClose() {
          init();
          editForm.showEdit = false;
        },
      })
    } else {
      ElMessage.error(res.msg || "修改失败")
    }
  } catch (error) {
    console.error("修改失败:", error)
    ElMessage.error("修改失败: " + (error.message || "未知错误"))
  }
}

// 取消编辑
const cancelEdit = () => {
  editForm.showEdit = false
}

onMounted(() => {
  init()
})
</script>

<template>
  <h1>用户管理
    <el-button type="danger" @click="delSelected" icon="Delete">批量删除</el-button>
  </h1>

  <!-- 搜索表单 -->
  <el-form :inline="true" :model="data.searchForm" class="search-form">
    <el-form-item label="搜索类型">
      <el-select v-model="data.searchForm.searchKey" placeholder="请选择搜索类型">
        <el-option label="用户ID" value="userId"></el-option>
        <el-option label="邮箱" value="email"></el-option>
        <el-option label="昵称" value="nickname"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="搜索内容">
      <el-input
          v-model="data.searchForm.searchValue"
          placeholder="请输入搜索内容"
          clearable
          @keyup.enter="handleSearch"
      ></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置搜索</el-button>
    </el-form-item>
  </el-form>

  <el-table ref="tableRef" :data="data.tableData" style="width: 100%" @sort-change="handleSortChange">
    <el-table-column type="selection" width="50"></el-table-column>
    <el-table-column label="用户ID" prop="userId" width="120" sortable></el-table-column>
    <el-table-column label="邮箱" prop="email" width="120"></el-table-column>
    <el-table-column label="昵称" prop="nickname" width="120"></el-table-column>
    <el-table-column label="注册时间" prop="registerTime" width="200" sortable></el-table-column>
    <el-table-column label="状态" prop="status" width="120" sortable>
      <template #default="scope">
        <span v-if="scope.row.status === 1">正常</span>
        <span v-else-if="scope.row.status === 0">禁言</span>
        <span v-else>封号</span>
      </template>
    </el-table-column>
    <el-table-column label="禁言结束时间" prop="muteEndTime" width="200">
      <template #default="scope">
        <span v-if="scope.row.status === 0">{{ scope.row.muteEndTime }}</span>
        <span v-else></span>
      </template>
    </el-table-column>    <el-table-column label="最后一次登录时间" prop="lastLoginTime" width="200" sortable></el-table-column>
    <el-table-column label="删除用户" #default="scope">
      <el-button type="danger" icon="delete" circle small @click="del(scope.row.userId)"></el-button>
    </el-table-column>
    <el-table-column width="150px" label="修改用户状态（1-正常，0-禁言，-1-封号）" #default="scope">
      <el-button type="primary" icon="edit" circle small @click="editUserStatus(scope.row)"></el-button>
    </el-table-column>
  </el-table>

  <!-- 分页查询 -->
  <el-pagination
      background
      style="margin-top: 30px"
      :total="data.total"
      :current-page="data.page"
      :page-size="data.limit"
      @current-change="jump"
      layout="total, prev, pager, next, jumper"
  />

  <!-- 编辑用户状态对话框 -->
  <el-dialog :close-on-click-modal="false" v-model="editForm.showEdit" title="修改用户状态" style="width: 40%">
    <el-form label-width="120">
      <el-form-item label="用户ID">
        <el-input v-model="editForm.userId" disabled style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="editForm.status" style="width: 200px">
          <el-option label="正常" value="1"></el-option>
          <el-option label="禁言" value="0"></el-option>
          <el-option label="封号" value="-1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="cancelEdit">取消</el-button>
      <el-button type="primary" @click="submitEdit">确定</el-button>
    </template>

  </el-dialog>

</template>

<style scoped>.search-form {
  margin-bottom: 20px;
}
</style>
